package aws

import (
	"fmt"
	"strings"
	"regexp"
	"strconv"
)

var attrNameRe *regexp.Regexp = regexp.MustCompile(`^Attribute\.([0-9]+)\.Name$`)

type Attribute struct {
	Name, Value string
}

type MultiValue []string

func (mv MultiValue) String() string {
	if len(mv) == 1 {
		return mv[0]
	}

	return strings.Join(mv, ", ")
}

type MultiMap map[string]MultiValue

func (a Attribute) String() string {
	return a.Name + ": " + a.Value
}

type AttributeList []Attribute

func (al AttributeList) AddToParams(params map[string]string) map[string]string {
	if params == nil {
		params = make(map[string]string, len(al))
	}

	// Find index of largest existing attribute in params.
	offset := 1
	for name, _ := range params {
		m := attrNameRe.FindStringSubmatch(name)
		if len(m) == 2 {
			n, _ := strconv.Atoi(m[1])
			if n >= offset {
				offset = n
			}
		}
	}

	for i, attr := range al {
		params[fmt.Sprintf("%s.%d.Name", attr.Name, i+offset)] = attr.Name
		params[fmt.Sprintf("%s.%d.Value", attr.Name, i+offset)] = attr.Value
	}

	return params
}

func (al AttributeList) ToMap() map[string]string {
	m := make(map[string]string, len(al))
	for _, attr := range al {
		m[attr.Name] = attr.Value
	}
	return m
}

func (al AttributeList) ToMultiMap() map[string]MultiValue {
	m := make(map[string]MultiValue, len(al))
	for _, attr := range al {
		mv, ok := m[attr.Name]
		if !ok {
			m[attr.Name] = MultiValue{attr.Value}
		} else {
			mv = append(mv, attr.Value)
		}
	}
	return m
}

func MapToAttributeList(m map[string]string) AttributeList {
	al := make(AttributeList, 0, len(m))
	for k, v := range m {
		al = append(al, Attribute{k, v})
	}
	return al
}
